<?php
namespace app\common\service\finance;



use app\admin\model\user\User;
use app\admin\model\user\UserBill;
use app\admin\model\user\UserWithdraw;
use app\common\service\BaseService;

class WithdrawalAudit extends BaseService
{

    /**
     * Author:Yingbo Sun
     * 提现审核通过
     * @param $row
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function pass($id)
    {
        if (empty($id)){
            return self::fail('参数错误');
        }
        $res = UserWithdraw::where('id',$id)->find();
        //查询出用户信息
        $user = User::where('id',$res->uid)->find();
        if ($user->isEmpty()) {
            return self::fail('审核失败，用户不存在');
        }
        //使用php高精密函数 计算余额
        $money = bcsub($user->money, $res->cash_price, 2);
        self::beginTrans();
        try {
            //扣除用户真实余额
            $where = ['id'=>$res->uid];
            $user->update(['money' => $money],$where);
            UserWithdraw::where('id', $res->id)->update(['is_status' => 1]);
            $event = '提现成功';
            //监听提现操作
            event('onWithdraw', $event);
            self::commitTrans();
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::fail($e->getMessage());
        }
        return self::success('提现申请成功');
    }

    /**
     * Author:Yingbo Sun
     * 提现审核不通过
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function failWith($id)
    {
        if (empty($id)){
            return self::fail('参数错误');
        }
        $res = UserWithdraw::where('id',$id)->find();
        $user = User::where('id',$res->uid)->find();
        if ($user->isEmpty()) {
            return self::fail('审核失败，订单不存在');
        }
        //使用php高精密函数 计算余额
        $money = bcadd($user->money, $res->cash_price, 2);
        self::beginTrans();
        try {
            $where = ['id'=>$user->id];
            //实现回余额操作
            $user->update(['fake_money' => $money],$where);
            UserWithdraw::where('id', $id)->update(['is_status' => 2]);
            $event = '提现失败';
            //监听提现操作
            event('onWithdraw', $event);
            self::commitTrans();
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::fail($e->getMessage());
        }
        return self::success('操作成功');
    }
}